<template>
  <div>
    <div class="form_sub">
      <draggable
        :list="dataComponents"
        tag="ul"
        v-bind="{ group: { name: 'people', pull: 'clone', put: false }, sort: false, ghostClass: 'ghost' }"
        @end="handleMoveEnd"
        @start="handleMoveStart"
        :move="handleMove"
      >
        <li
          class="form-edit-widget-label"
          :class="{ 'no-put': item.type == 'divider' }"
          v-for="(item, index) in dataComponents"
          :key="index"
        >
          <a> <i class="icon iconfont" :class="item.icon"></i> <span>{{ item.name }}</span> </a>
        </li>
      </draggable>
    </div>
    <div class="form_making">
      <!--//左边--拖到区域-->
      <div class="center-container">
        <a-layout-header class="btn-bar" style="height: 45px;display: none;">
          <slot name="action" />
          <a-button type="text" size="small" icon="el-icon-upload2" @click="handleUpload">
            <!-- {{ $t('fm.actions.import') }} -->
            导入JSON
          </a-button>
          <a-button type="text" size="small" icon="el-icon-delete" @click="handleClear">
            <!-- {{ $t('fm.actions.clear') }} -->
            清空
          </a-button>
          <a-button type="text" size="small" icon="el-icon-view" @click="handlePreview">
            <!-- {{ $t('fm.actions.preview') }} -->
            预览
          </a-button>
          <a-button type="text" size="small" icon="el-icon-tickets" @click="handleGenerateJson">
            <!-- {{ $t('fm.actions.json') }} -->
            生成JSON
          </a-button>
          <!-- <a-button type="text" size="small" icon="el-icon-document" @click="handleGenerateCode">
            {{ $t('fm.actions.code') }}
          </a-button> -->
        </a-layout-header>
        <a-layout-content :class="{ 'widget-empty': widgetForm.list.length == 0 }" class="widget-layout">
          <widget-form
            v-if="!resetJson"
            ref="widgetForm"
            :data="widgetForm"
            :select.sync="widgetFormSelect"
          ></widget-form>
        </a-layout-content>
      </div>
      <!--//右边--字段属性、表单属性-->
      <div class="widget-config-container">
        <a-layout>
          <a-layout-header height="45px" style="padding:0;">
            <div :class="{ active: configTab == 'widget' }" class="config-tab" @click="handleConfigSelect('widget')">
              <!-- {{ $t('fm.config.widget.title') }} -->
              字段属性
            </div>
            <div :class="{ active: configTab == 'form' }" class="config-tab" @click="handleConfigSelect('form')">
              <!-- {{ $t('fm.config.form.title') }} -->
              表单属性
            </div>
          </a-layout-header>
          <a-layout-content class="config-content" style="background-color: #fff;">
            <widget-config v-show="configTab == 'widget'" :data="widgetFormSelect" />
            <form-config v-show="configTab == 'form'" :data="widgetForm.config" />
          </a-layout-content>
        </a-layout>
      </div>
    </div>
    <!--//预览弹窗-->
    <cus-dialog ref="widgetPreview" :visible="previewVisible" @on-close="previewVisible = false" width="1000px" form>
      <generate-form
        v-if="previewVisible"
        ref="generateForm"
        :data="widgetForm"
        :value="widgetModels"
        :remote="remoteFuncs"
        insite="true"
        @on-change="handleDataChange"
      >
        <!-- <template v-slot:blank="scope">
          Width <el-input v-model="scope.model.blank.width" style="width: 100px"></el-input>
          Height <el-input v-model="scope.model.blank.height" style="width: 100px"></el-input>
        </template>-->
      </generate-form>

      <template slot="action">
        <a-button type="primary" @click="handleTest">获取数据</a-button>
        <a-button @click="handleReset">重置</a-button>
      </template>
    </cus-dialog>
    <!--//生成JSON弹窗-->
    <cus-dialog ref="jsonPreview" :visible="jsonVisible" @on-close="jsonVisible = false" width="800px" form>
      <!-- <div id="jsoneditor" style="height: 400px;width: 100%; word-break: break-all; white-space: normal;">
        {{ jsonTemplate }}
      </div> -->
      <editor v-model="jsonTemplate" @init="editorInit" lang="html" theme="chrome" width="100%" height="400" />
      <template slot="action">
        <a-button type="primary" class="json-btn" :data-clipboard-text="jsonCopyValue">复制</a-button>
      </template>
    </cus-dialog>
    <!--//导入弹窗-->
    <cus-dialog
      ref="uploadJson"
      :visible="uploadVisible"
      width="800px"
      form
      @on-close="uploadVisible = false"
      @on-submit="handleUploadJson(jsonEg)"
    >
      <!-- <el-alert :title="$t('fm.description.uploadJsonInfo')" type="info" /> -->
      <editor v-model="jsonEg" @init="editorInit" lang="html" theme="chrome" width="100%" height="400" />
      <!-- <div id="uploadeditor" style="height: 400px;width: 100%;">{{ jsonEg }}</div> -->
    </cus-dialog>
  </div>
</template>

<script>
  import Draggable from 'vuedraggable'
  import Clipboard from 'clipboard'
  // 基础字段、高级字段、布局字段
  import { basicComponents, advanceComponents, layoutComponents } from '@/components/formMaking/componentsConfig.js'
  import WidgetForm from '@/components/formMaking/WidgetForm' // 拖拽表单区域
  import CusDialog from '@/components/formMaking/CusDialog' // 导入JSON
  import WidgetConfig from '@/components/formMaking/WidgetConfig' // 字段属性
  import FormConfig from '@/components/formMaking/FormConfig' // 表单属性
  import GenerateForm from '@/components/formMaking/GenerateForm' // 预览
  export default {
    name: 'Generate',
    components: {
      // eslint-disable-next-line vue/no-unused-components
      Clipboard,
      Draggable,
      WidgetForm,
      CusDialog,
      WidgetConfig,
      FormConfig,
      GenerateForm,
      // eslint-disable-next-line vue/no-unused-components
      editor: require('vue2-ace-editor'),
    },
    data() {
      return {
        jsonData: {
          list: [],
          config: {
            labelWidth: 4,
            labelPosition: 'right',
            size: 'small',
            customClass: '',
            ui: 'element',
            layout: 'horizontal',
            labelCol: 3,
          },
        },
        dataComponents: [],
        basicComponents,
        layoutComponents,
        advanceComponents,
        resetJson: false,
        widgetForm: {
          list: [],
          config: {
            labelWidth: 4,
            labelPosition: 'right',
            size: 'small',
          },
        },
        widgetModels: {},
        widgetFormSelect: null,
        jsonVisible: false,
        previewVisible: false,
        codeVisible: false,
        uploadVisible: false,
        jsonTemplate: '',
        jsonCopyValue: '',
        uploadEditor: null,
        configTab: 'widget',
        jsonEg: `{
          'list': [],
          'config': {
            'labelWidth': 4,
            'labelPosition': 'top',
            'size': 'small'
          }
        }`,
        remoteFuncs: {
          func_test(resolve) {
            setTimeout(() => {
              const options = [
                { id: '1', name: '1111' },
                { id: '2', name: '2222' },
                { id: '3', name: '3333' },
              ]
              resolve(options)
            }, 2000)
          },
          // funcGetToken(resolve) {
          //   request
          //     .get('http://tools-server.xiaoyaoji.cn/api/uptoken')
          //     .then(res => {
          //       resolve(res.uptoken)
          //     })
          // },
          upload_callback(response, file, fileList) {
            console.log('callback', response, file, fileList)
          },
        },
      }
    },
    async created() {
      await this._loadComponents()
      await (this.dataComponents = [...this.basicComponents, ...this.advanceComponents, ...this.layoutComponents])
      // console.log(this.dataComponents)
      // this.jsonData.list = [...this.basicComponents, ...this.advanceComponents, ...this.layoutComponents]
    },
    watch: {
      widgetForm: {
        deep: true,
        handler: function(val) {
          // console.log(this.$refs.widgetForm)
        },
      },
    },
    methods: {
      editorInit: function() {
        require('brace/ext/language_tools') //language extension prerequsite...
        require('brace/mode/html')
        require('brace/mode/javascript') //language
        require('brace/mode/less')
        require('brace/theme/chrome')
        require('brace/snippets/javascript') //snippet
      },
      _loadComponents() {
        this.basicComponents = this.basicComponents.map(item => {
          return {
            ...item,
            name: this.$t(`fm.components.fields.${item.type}`)
          }
        })
        this.advanceComponents = this.advanceComponents.map(item => {
          return {
            ...item,
            name: this.$t(`fm.components.fields.${item.type}`)
          }
        })
        this.layoutComponents = this.layoutComponents.map(item => {
          return {
            ...item,
            name: this.$t(`fm.components.fields.${item.type}`)
          }
        })
      },
      handleSubmit() {
        this.$refs.generateForm
          .getData()
          .then(data => {
            alert(JSON.stringify(data))
          })
          .catch(e => {})
      },
      handleMoveEnd(evt) {
        // console.log('end', evt)
      },
      handleMoveStart({ oldIndex }) {
        // console.log('start', oldIndex, this.basicComponents)
      },
      handleMove() {
        return true
      },
      // 导入
      handleUpload() {
        this.uploadVisible = true
        this.$nextTick(() => {
          // this.uploadEditor = ace.edit('uploadeditor')
          // this.uploadEditor.session.setMode('ace/mode/json')
        })
      },
      // 确定导入
      handleUploadJson(json) {
        try {
          // this.setJSON(JSON.parse(this.uploadEditor.getValue()))
          this.setJSON(JSON.parse(json))
          this.uploadVisible = false
        } catch (e) {
          this.$message.error(e.message)
          this.$refs.uploadJson.end()
        }
      },
      // 清空
      handleClear() {
        this.widgetForm = {
          list: [],
          config: {
            labelWidth: 100,
            labelPosition: 'right',
            size: 'small',
            customClass: '',
          },
        }
        this.widgetFormSelect = {}
      },
      // 生成JSON
      getJSON() {},
      // 生成代码
      getHtml() {},
      // 导入JSON
      setJSON(json) {
        this.widgetForm = json
        if (json.list.length > 0) {
          this.widgetFormSelect = json.list[0]
        }
      },
      // 预览
      handlePreview() {
        this.previewVisible = true
      },
      // 获取数据
      handleTest() {
        this.$refs.generateForm
          .getData()
          .then(data => {
            alert(JSON.stringify(data))
            this.$refs.widgetPreview.end()
          })
          .catch(e => {
            this.$refs.widgetPreview.end()
          })
      },
      // 重置
      handleReset() {
        this.$refs.generateForm.reset()
      },
      // 生成代码
      handleGenerateCode() {},
      // 生成JSON
      handleGenerateJson() {
        this.jsonVisible = true
        this.jsonTemplate = JSON.stringify(this.widgetForm)
        // this.$nextTick(() => {
        // const editor = ace.edit('jsoneditor')
        // editor.session.setMode('ace/mode/json')

        if (!this.jsonClipboard) {
          this.jsonClipboard = new Clipboard('.json-btn')
          this.jsonClipboard.on('success', e => {
            this.$message.success(this.$t('fm.message.copySuccess'))
          })
        }
        this.jsonCopyValue = JSON.stringify(this.widgetForm)
        // })
      },
      handleConfigSelect(value) {
        this.configTab = value
      },
      handleDataChange(field, value, data) {
        console.log(field, value, data)
      },
    },
    // async mounted() {
    //   await this._loadComponents()
    //   await (this.dataComponents = [...basicComponents, ...advanceComponents, ...layoutComponents])
    //   console.log(this.dataComponents)
    //   // this.jsonData.list = [...basicComponents, ...advanceComponents, ...layoutComponents]
    // }
  }
</script>

<style lang="less" scoped></style>
